package models

import (
	"errors"
	"github.com/sirupsen/logrus"
)

// LianMerchantUpload 保存联动上传的图片
type LianMerchantUpload struct {
	ID             uint   `json:"id" form:"id" gorm:"primary_key;AUTO_INCREMENT;comment:'id'"`
	MerchantId     int    `json:"merchant_id" gorm:"comment:'商户id'"`
	TempMerchantId int    `json:"temp_merchant_id" gorm:"comment:'临时商户id'"`
	FileId         string `json:"file_id" gorm:"comment:'联动返回的图片id'"`
	Remarks        string `json:"remarks" gorm:"comment:'图片备注名'"`
}

func LianMerchantUploadAddList(list []map[string]interface{}) error {
	for _, m := range list {
		err := db.Model(&LianMerchantUpload{}).Create(&m).Error
		if err != nil {
			logrus.WithError(err).Errorf("保存联动上传的图片失败：%v", err)
			return errors.New("保存联动上传的图片失败")
		}
	}
	return nil
}

func LianMerchantUploadAdd(mapd map[string]interface{}) error {
	var upload LianMerchantUpload
	db.Model(&LianMerchantUpload{}).Where("temp_merchant_id = ? and remarks = ?", mapd["temp_merchant_id"], mapd["remarks"]).Scan(&upload)
	if upload.ID == 0 {
		err := db.Model(&LianMerchantUpload{}).Create(&mapd).Error
		if err != nil {
			logrus.WithError(err).Errorf("保存联动上传的图片失败：%v", err)
			return errors.New("保存联动上传的图片失败")
		}
	} else {
		db.Model(&upload).Update("file_id", mapd["file_id"])
	}
	return nil
}

func LianMerchantUpdate(tempMerchantId interface{}, mapd map[string]interface{}) error {
	var upload LianMerchantUpload
	db.Model(&LianMerchantUpload{}).Where("temp_merchant_id = ?", tempMerchantId).Scan(&upload)
	if upload.ID == 0 {
		return errors.New("记录不存在")
	}

	db.Model(&LianMerchantUpload{}).Where("temp_merchant_id = ?", tempMerchantId).Updates(&mapd)
	return nil
}

// GetLianMerchantPicId 获取图片id
func GetLianMerchantPicId(merchantId interface{}) map[string]string {
	var upload []*LianMerchantUpload
	db.Model(&LianMerchantUpload{}).Where("merchant_id = ?", merchantId).Scan(&upload)

	var result = make(map[string]string)
	for _, merchantUpload := range upload {
		result[merchantUpload.Remarks] = merchantUpload.FileId
	}

	return result
}
